﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core;
using System.Diagnostics;
using COFE.Core;

namespace COFE.Core
{
    /// <summary>
    /// Entry related Utils.
    /// </summary>
    public static class EntryUtils
    {
        /// <summary>
        /// Return Guid.Empty if entries == null, otherwise return it's hash guid.
        /// </summary>
        /// <param name="entries"></param>
        /// <returns></returns>
        public static Guid GetIdOrDefault(this IFileSystemInfo entry)
        {
            if (entry == null)
                return Guid.Empty;
            else return entry.GetId();
        }

        /// <summary>
        /// Return Null if entries == null, otherwise return it's parse name.
        /// </summary>
        /// <param name="entries"></param>
        /// <returns></returns>
        public static string GetParseNameOrDefault(this IFileSystemInfo entry)
        {
            if (entry == null)
                return null;
            else return entry.ParseName;
        }

        public static bool HasParent(this IFileSystemInfo entry, IDirectoryInfo parent)
        {
            if (parent == null)
                return false;

            IFileSystemInfo current = entry.Parent;            
            while (current != null && !parent.Equals(current))
                current = current.Parent;
            return (current != null);
        }

        public static bool HasChild(this IDirectoryInfo parent, IFileSystemInfo child)
        {
            return child.HasParent(parent);
        }


        public static T GetEmbeddedEntry<T>(IInternalFileSystemInfoExA entry)
        {
            T retVal = default(T);

            Func<IInternalFileSystemInfoExA, bool> getEmbEntry = (e) =>
            {
                PropertyPair ppair = e.GetProperty(InternalProperties.EmbeddedEntry);;
                if (ppair == null)
                    throw new System.IO.FileNotFoundException(entry.Name);

                if (ppair.Value is T)
                {
                    retVal = (T)ppair.Value;
                    return true;
                }
                return false;
            };

            if (getEmbEntry(entry))
                return retVal;

            if (entry.GetProperty(DirectoryInfoProperties.IsFileBasedFS).ValueAsBoolean)
            {
                var fbFSEntry = entry.GetProperty(DirectoryInfoProperties.FileBasedFSFile).Value as IInternalFileSystemInfoExA;
                if (getEmbEntry(fbFSEntry))
                    return retVal;
            }

            throw new Exception("Wrong EmbeddedEntry type.");
        }
    
    }
}
